<template>
  <div v-if="permissions.length === 0" class="empty-permission">
    <el-empty description="暂无可用功能权限，请联系管理员" />
  </div>

  <div v-else class="home-component">
    <!-- 页面内容区域 -->
    <div class="page-content">
      <div class="content-card">
        <h3>欢迎使用scm供应链管理系统</h3>
        <p>这是一个集成了资金管理、账户管理、采购管理、销售管理、库存管理和报表分析的企业资源计划系统。</p>
      </div>

      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-title">资金总额</div>
          <div class="stat-value">¥ 5,682,450</div>
          <div class="stat-change">↑ 12.5% 较上月</div>
        </div>
        <div class="stat-card">
          <div class="stat-title">本月销售额</div>
          <div class="stat-value">¥ 2,156,800</div>
          <div class="stat-change">↑ 8.3% 较上月</div>
        </div>
        <div class="stat-card">
          <div class="stat-title">采购支出</div>
          <div class="stat-value">¥ 1,245,600</div>
          <div class="stat-change">↑ 5.7% 较上月</div>
        </div>
        <div class="stat-card">
          <div class="stat-title">库存价值</div>
          <div class="stat-value">¥ 3,758,300</div>
          <div class="stat-change">↓ 2.4% 较上月</div>
        </div>
      </div>


      <div class="content-card">
        <h3>部门员工分布</h3>
        <div ref="chartRef" class="chart-container"></div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useAuthStore } from '@/store'
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from "element-plus";

const authStore = useAuthStore()
const permissions = computed(() => authStore.permissions)
const chartRef = ref(null);
let myChart = null;

const staffList = ref([])

const getStaffList = async () => {
  try {
    const res = await axios.get('/api/basic/enterprise/getStaffCountByDepartment')
    if (res.data.code === 5200) {
      staffList.value = res.data.staffList
      // 数据加载完成后立即渲染图表
      renderChart();

    } else {
      ElMessage.error('数据获取失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const renderChart = () => {
  // 销毁已有实例（防止重复初始化）
  if (myChart) {
    myChart.dispose();
  }

  // 初始化新图表
  myChart = echarts.init(chartRef.value);

  // 显示加载动画
  myChart.showLoading({
    text: '正在加载数据...',
    color: '#6c757d', // 加载动画的颜色
    maskColor: 'rgba(255, 255, 255, 0.8)', // 背景颜色
    zlevel: 0,
  });

  if (!staffList.value || staffList.value.length === 0) {
    myChart.setOption({
      title: {
        text: '暂无部门数据',
        left: 'center',
        top: 'middle',
        textStyle: { color: '#999' }
      }
    });
    return;
  }

  const option = {
    title: {
      text: '',
      left: 'center'
    },
    // 配置提示信息
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'shadow'
      }
    },
    // 系列列表
    series: [
      {
        name: '部门人数',
        type: 'pie',  // 设置图表类型为饼图
        radius: '55%', // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
        data: staffList.value.map(item => ({   // 数据数组
          name: item.departmentName,
          value: item.staffCount
        })),
        // itemStyle: {
        //   color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //     { offset: 0, color: '#5470c6' },
        //     { offset: 1, color: '#91cc75' }
        //   ])
        // }
      }
    ]
  };

  myChart.setOption(option);
  // 隐藏加载动画
  myChart.hideLoading();
};

// 窗口大小变化时重绘
const handleResize = () => {
  myChart?.resize();
};

onMounted(() => {
  getStaffList();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
});

</script>

<style scoped>
.home-component {
  width: 100%;
}

.page-content {
  flex: 1;
  padding: 24px;
  background: #f5f7fa;
  overflow-y: auto;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  padding: 24px;
  margin-bottom: 24px;
}

.content-card h3 {
  margin-bottom: 16px;
  color: #066981;
  font-weight: 600;
}

/* 新增：图表容器 */
.chart-container {
  width: 100%;
  height: 400px;
  margin-top: 16px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.stat-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #066981;
}

.stat-change {
  margin-top: 8px;
  font-size: 12px;
  color: #52c41a;
}

.stat-change.negative {
  color: #f5222d;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-content {
    padding: 16px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .content-card {
    padding: 16px;
  }

  .chart-container {
    height: 300px;
  }
}
</style>